package cn.hybrid.nio.channel;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class ReadByFileChannel {
    /**
     * Buffer顾名思义：缓冲区，实际上是一个容器，一个连续数组。
     * Channel提供从文件、网络读取数据的渠道，但是读写的数据都必须经过Buffer
     *
     *
     * client---数据--->
     *          buffer--数据--->channel--数据-->
     *                                   channel--数据->buffer
     *                                                   ---数据--->server
     *
     */

    public static String readRandomAccessFile(String filePath){
        StringBuilder stringBuilder = new StringBuilder();
        RandomAccessFile aFile = null;
        try {
            aFile = new RandomAccessFile(filePath, "rw");
            FileChannel fileChannel = aFile.getChannel();
            //分配空间
            ByteBuffer buf = ByteBuffer.allocate(1024);
            //写入数据到Buffer
            int bytesRead = fileChannel.read(buf);
            System.err.println("Buffer大小"+bytesRead);
            while (bytesRead != -1) {
                //调用filp()方法
                buf.flip();
                while (buf.hasRemaining()) {
                    //从Buffer中读取数据
                    stringBuilder.append((char) buf.get());
                }
                //调用clear()方法或者compact()方法
                buf.compact();
                //从Channel写到Buffer
                bytesRead = fileChannel.read(buf);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (aFile != null) {
                    aFile.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return stringBuilder.toString();
    }



}
